﻿package pluginfw.nio.message
{
    import flash.utils.*;
    import pluginfw.*;
    import pluginfw.nio.encrypt.*;

    public class BufferMessage extends Object implements IBufferMessage
    {
        protected var buffer:ByteArray;
        protected var compressed:Boolean = false;
        protected var body:ByteArray;

        public function BufferMessage(param1:Boolean = false)
        {
            this.compressed = param1;
            this.buffer = new ByteArray();
            return;
        }// end function

        function parse(param1:int, param2:int, param3:int, param4:ByteArray) : void
        {
            this.buffer.position = 0;
            this.buffer.writeInt(param1);
            this.buffer.writeByte(0);
            this.buffer.writeShort(param2);
            this.buffer.writeShort(param3);
            param4.readBytes(this.buffer, this.buffer.position, param1 - 5);
            return;
        }// end function

        public function getSize() : int
        {
            this.buffer.position = 0;
            return this.buffer.readInt();
        }// end function

        public function getMessageId() : int
        {
            this.buffer.position = 5;
            return this.buffer.readShort();
        }// end function

        public function getCrc() : int
        {
            this.buffer.position = 7;
            return this.buffer.readUnsignedShort();
        }// end function

        public function getType() : int
        {
            this.buffer.position = 4;
            return this.buffer.readByte();
        }// end function

        public function getGroup() : int
        {
            this.buffer.position = 9;
            return this.buffer.readUnsignedByte();
        }// end function

        public function getCmd() : int
        {
            this.buffer.position = 10;
            return this.buffer.readUnsignedShort();
        }// end function

        public function getBuffer() : ByteArray
        {
            this.buffer.position = 0;
            return this.buffer;
        }// end function

        public function getBody() : ByteArray
        {
            if (this.body == null)
            {
                this.body = new ByteArray();
                this.buffer.position = 12;
                this.buffer.readBytes(this.body);
                CRC16.decode(this.body, this.getCrc());
                if (this.compressed)
                {
                    this.body.uncompress();
                }
            }
            this.body.position = 0;
            return this.body;
        }// end function

        public function toString() : String
        {
            return StringUtil.substitute("BufferMessage:messageid={4},crc={0},group={1},cmd={2},body={3}", this.getCrc(), this.getGroup(), this.getCmd(), this.getBody(), this.getMessageId());
        }// end function

    }
}
